package stalker;

import java.util.GregorianCalendar;
import java.util.HashMap;

/**
 * Static class that stores bindings from keys to stalkers
 */

public class StalkerCatalog {
  
  private final HashMap<Long, Stalker> bindings = new HashMap<Long, Stalker>();
  
  private void checkRep() {
    assert (bindings != null) :
      "StalkerCatalog: field may not be null";
  }
  
  /**
   * Adds a stalker and updates all corresponding fields
   * @requires new_stalker is not null, stalker is new
   * @param new_stalker  the new stalker to be added
   * @complexity A(1)
   */
  public synchronized void addNewStalker(Stalker new_stalker) {
    assert new_stalker != null;
    assert Stalker.SERVER;
    assert (!(bindings.containsKey(new_stalker.getID()))) :
      "StalkerCatalog: Stalker already present";
    bindings.put(new_stalker.getID(), new_stalker);    
    checkRep();
  }
  
  /**
   * Retrieves a stalker given its ID
   * <p>
   * If not in server creates a dummy stalker
   * @requires id is positive, there's a stalker with the given ID
   * @param id the ID of the stalker that's being searched
   * @return the Stalker whose ID is <code>id</code>
   */
  public synchronized Stalker getStalker(long id) {
    assert (id >= 0L) :
      "ID should be positive whereas it is : " + id;
    if (!Stalker.SERVER) {
      //this part is deprecated
      assert false;
      return new Stalker(id, new GregorianCalendar(), "Not Known");
    }
    assert (bindings.containsKey(id));
    return bindings.get(id);
  }
  
  /**
   * Checks if an ID is registered
   * @param id id to be checked
   * @return true iff id is a stalker
   */
  public synchronized boolean contains(long id) {
    assert Stalker.SERVER;
    return bindings.containsKey(id);
  }
  
}
